package com.gxa.employment.controller;

import com.gxa.employment.common.Result;
import com.gxa.employment.entity.dto.PageBean;
import com.gxa.employment.entity.pojo.Permission;
import com.gxa.employment.entity.vo.PageVo;
import com.gxa.employment.mapper.PermissionMapper;
import com.gxa.employment.mapper.RoleMapper;
import com.gxa.employment.service.PermissionService;
import com.gxa.employment.service.RoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * <p>
 * 系统权限表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-03-25
 */
@RestController
@RequestMapping("/permission")
@Tag(name = "权限管理", description = "权限相关操作API")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleMapper roleMapper;

    @PostMapping("/add")
    @Operation(summary = "添加权限")
    @Transactional(rollbackFor = Throwable.class)  //事务
    public Result add(@RequestBody Permission permission) {
        permissionService.save(permission);
        //这里的1应该是当前角色，使用ThreadLocal获取
        roleMapper.addPermissionForRole(1, permission.getPermId());
        return Result.success();
    }

    @PutMapping("/update")
    @Operation(summary = "修改权限")
    public Result update(@RequestBody Permission permission) {
        permissionService.updateById(permission);
        return Result.success();
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除权限")
    @Transactional(rollbackFor = Throwable.class)  //事务
    public Result delete(@RequestParam Integer id) {
        //删除权限
        permissionService.deleteAllPermission(id);
        return Result.success();
    }


    /**
     * 权限分页模糊查询接口
     * 该接口用于根据分页条件进行权限的模糊查询，并返回查询结果
     *
     * @param pageBean 分页查询条件，包含页码、每页数量、查询关键字等
     * @return 返回查询结果的分页对象，封装在Result对象中
     */
    @PostMapping("/getByPage")
    @Operation(summary = "权限分页模糊查询")
    public Result<PageVo<Permission>> getByPage(@RequestBody PageBean pageBean) {
        return Result.success(permissionService.getByPage(pageBean));
    }

    @GetMapping("/getMenuList")
    @Operation(summary = "获取登录用户的菜单权限")
    public Result<List<Permission>> getMenuList() {
        List<Permission> menuList = permissionService.getMenuList();
        return Result.success(menuList);
    }
}
